const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const {
  getRestaurant,
  addRestaurant,
  deleteRestaurant,
  getRestaurantDetail,
  updateRestaurantStatus,
} = require("../utils/sql");

// 设置 multer 的存储方式为 diskStorage，可以将上传的文件存储在磁盘中
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 设置文件存储位置
    cb(null, path.join(__dirname, "../../public/images/rest"));
  },
  filename: function (req, file, cb) {
    // 设置文件名
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage: storage });

// 餐厅表
router.get("/restaurant", async (req, res) => {
  const result = await getRestaurant();
  res.send({
    code: 200,
    msg: "success",
    data: result,
  });
});

// 增加餐厅
// 参数 restaurant_id
// restaurant_name
// address
// contact_number
// image_url
router.post("/addrestaurant", upload.single("image"), async (req, res) => {
  console.log(req.file);
  const result = await addRestaurant({
    ...req.body,
    image_url: req.file.filename, // 使用上传的文件名作为 image_url
  });
  res.send({
    code: 200,
    msg: "success",
    data: result,
  });
});

// 删除餐厅
// 参数 restaurant_id
router.post("/deleterestaurant", async (req, res) => {
  console.log(req.body);
  const { id } = req.body;
  const result = await deleteRestaurant(id);
  res.send({
    code: 200,
    msg: "success",
    data: result,
  });
});
// 餐厅详情
// 参数 id
router.post("/restaurantdetail", async (req, res) => {
  console.log(req.body);
  const { id } = req.body;
  const result = await getRestaurantDetail(id);
  res.send({
    code: 200,
    msg: "success",
    data: result,
  });
});


// 餐厅上架下架状态
// 参数 id, status
router.post("/restaurantstatus", async (req, res) => {
  console.log(req.body);
  const { id, newStatus } = req.body;
  const result = await updateRestaurantStatus(id, newStatus);
  res.send({
    code: 200,
    msg: "success",
    data: result,
  });
});

module.exports = router;
